﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;

namespace Bootstrap.Security
{
    /// <summary>
    /// BA 后台多数据库适配帮助类
    /// </summary>
    public static class BAAdapterHelper
    {
        // 读取配置文件中 AuthHost 配置
        private static Lazy<BootstrapAdminHttpClient> _client;

        internal static void AddBootstrapAdminInterface(this IServiceCollection services)
        {
            _client = new Lazy<BootstrapAdminHttpClient>(() => services.BuildServiceProvider().GetRequiredService<BootstrapAdminHttpClient>());
        }

        private static T ExecuteRemoteAction<T>(string actionName, object data = null)
        {
            var task = _client.Value.PostAsJsonAsync<T>(actionName, data);
            task.Wait();
            return task.Result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="userName"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static IEnumerable<BootstrapMenu> RetrieveAppMenus(string appId, string userName, string url) => ExecuteRemoteAction<IEnumerable<BootstrapMenu>>("RetrieveAppMenus", new AppMenuOption() { AppId = appId, UserName = userName, Url = url });

        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static IEnumerable<string> RetrieveRolesByUrl(string url) => ExecuteRemoteAction<IEnumerable<string>>("RetrieveRolesByUrl", url);

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static IEnumerable<string> RetrieveRolesByUserName(string userName) => ExecuteRemoteAction<IEnumerable<string>>("RetrieveRolesByUserName", userName);

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<BootstrapDict> RetrieveDicts() => ExecuteRemoteAction<IEnumerable<BootstrapDict>>("RetrieveDicts");

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<BootstrapGroup> RetrieveGroups() => ExecuteRemoteAction<IEnumerable<BootstrapGroup>>("RetrieveGroups");

        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static BootstrapUser RetrieveUserByUserName(string userName) => ExecuteRemoteAction<BootstrapUser>("RetrieveUserByUserName", userName);
    }
}
